package com.feeyo.lib_baidutts.voice

import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioTrack
import android.os.Build
import androidx.annotation.RequiresApi
import java.io.BufferedInputStream
import java.io.DataInputStream
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.IOException

class PcmPlayer {

    private val sampleRateInHz = 16000

    private val player: AudioTrack

    private var bufferSize: Int

    init {
        bufferSize = AudioTrack.getMinBufferSize(sampleRateInHz, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT)

        player = AudioTrack.Builder()
                    .setAudioAttributes(AudioAttributes.Builder()
                            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                            .build())
                    .setAudioFormat(AudioFormat.Builder()
                            .setEncoding(AudioFormat.ENCODING_PCM_16BIT)
                            .setSampleRate(sampleRateInHz)
                            .setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
                            .build())
                    .setBufferSizeInBytes(bufferSize)
                    .build()
    }

    /**
     * 播放pcm文件
     */
    fun play(filePath: String) {
        var dis: DataInputStream? = null
        try {
            dis = DataInputStream(BufferedInputStream(FileInputStream(filePath)))
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }

        dis?.let {
            play(it)
        }
    }

    /**
     * 播放pcm文件
     * @param inputStream
     */
    fun play(inputStream: DataInputStream) {
        val data = ByteArray(bufferSize)

        player.play()

        while (true) {
            var i = 0

            try {
                while (inputStream.available() > 0 && i < data.size) {
                    data[i] = inputStream.readByte()
                    i++
                }

            } catch (e: IOException) {
                e.printStackTrace()
            }

            player.write(data, 0, data.size)

            if (i != bufferSize) {
                stop()
                break
            }
        }
    }

    fun stop() {
        player.stop()
        player.release()
    }
}